package com.tecklab.demo.jdk;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Deacription TODO
 * @Author sunking
 * @Date 2022/11/24} 上午5:15
 **/
public class SystemTest {
    public static void main(String[] args) throws InterruptedException {
        // 获取时间总次数
        int threadCount = 1000;

        // 单线程循环获取
        long singleStartTime = System.nanoTime();
        for(int i=0; i<threadCount; i++) {
            System.nanoTime();
        }
        long singleDeltaTime = System.nanoTime() - singleStartTime;
        System.out.println("单线程" + threadCount + "次耗时：" + singleDeltaTime + "ms");

        // 使用线程池，多线程并发获取
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(16, 16,
                60L, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1000));

        CountDownLatch subDownLatch = new CountDownLatch(threadCount);
        CountDownLatch mainCountDownLatch = new CountDownLatch(1);
        for(int i=0; i<threadCount; i++) {
            threadPoolExecutor.execute(() -> {
                try {
                    // 主线程先阻塞等待
                    mainCountDownLatch.await();
                    System.nanoTime();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    subDownLatch.countDown();
                }
            });
        }
        long startTime = System.nanoTime();
        // 主线程开始继续执行
        mainCountDownLatch.countDown();
        // 子线程等待线程池中其他活跃线程执行完
        subDownLatch.await();
        long deltaTime = System.nanoTime() - startTime;
        System.out.println("并发" + threadCount + "次耗时：" + deltaTime + "ms");

    }

}
